<?php

namespace app\common\model\sync;

use app\api\controller\mytool\SendMessage;
use app\api\controller\Pub;
use app\common\model\company\Company;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\user\User;
use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Request;

use think\Model;

class SyncCenter extends Model
{
     // 设置当前模型对应的完整数据表名称
        protected $table = 'sync_center';
        protected $pk = 'Id';

    const STATUS = [0 => '待执行', 1 => '执行中', 2 => '待补偿', 3 => '补偿错误', 4 => '已完成', 5 => '已取消'];

    const STATEINT        = 0; //创建状态
    const STATESTART      = 1; //等待执行（执行中）
    const STATEWAIT       = 2; //等待补偿
    const STATEERROR      = 3; //补偿错误
    const STATEOK         = 4; //执行成功
    const STATECANCEL     = 5; //已取消
    const STATEREQUESTERR = 6; //执行成功，返回失败
    const STATERETURNWAIT = 7; //执行错误 返回给客户修改后从新执行 -》发送成功
    const STATE_ERR_REQUEST_ERR = 8; //执行错误，返回个客户修改从新执行 -》发送失败
    const STATE_CANCEL_REQUEST_ERR = 9; //执行取消后通知客户    
    public function userInfo()
    {
        return $this->belongsTo(User::class, 'UpUserId', 'UserId');
    }

    public function getSynImgAttr($value)
    {
        if (!empty($value)) {
            return SYNC_URL.$value;
        } else {
            return '';
        }
    }

    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1 => '全部指令', 0 => '待执行', 1 => '执行中', 4 => '已完成', 5 => '已取消' , 7=>'执行错误'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }

    /**
     * 获取列表
     * @param  [type]  $data    [description]
     * @param  boolean $is_page [description]
     * @return [type]           [description]
     */
    public static function usergetlist($data, $is_page = true)
    {

        $where = [];

        if (!empty($data['where']['StartTime']) && $data['where']['StartTime'] != '') {
            $where[] = ['CreateTime', '>=', $data['where']['StartTime']];
        }
        if (!empty($data['where']['EndTime']) && $data['where']['EndTime'] != '') {
            $where[] = ['CreateTime', '<=', $data['where']['EndTime']];
        }
        $rdata = SyncCenter::where($where);


        $visible = ['Id','Type', 'CreateTime', 'Status', 'StatusText','userInfo.Name'];
        if (!empty($data['field'])) {
            $visible = array_merge($data['field'], $visible);
        }
        $data['order'] = 'CreateTime desc';

        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];

        if (!empty($data['field'])) {
            $rdata = $rdata->field($visible);
        }
        $rdata = $rdata->with('userInfo')->select();
       
        if (empty($data['field'])) {
            $rdata = $rdata->visible($visible);
        }

        $ndata['list'] = $rdata->toArray();
        $ndata['statetext'] = SyncCenter::getStatusText();
        
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }

    /**
     * 获取加密后的用户密码
     * @return [type] [description]
     */
    public static function getpassword($username, $password)
    {
        if (empty($username) || empty($password)) {
            return serr('程序错误');
        }
        $sb = SyncCenter::getsal();
        if (!$sb['code']) {
            return $sb;
        }
        $key     = $username . $sb['msg'] . $username;
        $payload = array(
            "iss" => "", //签发者 可以为空
            "aud" => "", //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time(), //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp" => time() + 259200, //token 过期时间
            "uid" => $password, //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
        );
        $jwt = JWT::encode($payload, $key, "HS256"); //加密
        return sok($jwt);
    }
    /**
     * 获取加密盐
     * @return [type] [description]
     */
    public static function getsal()
    {
        $sal = Cache::get('planjwt');
        if (empty($sal)) {
            try {
                $sal = SyncCenter::syncapi('index/getplanjwt', []);
                if (!$sal['code']) {
                    return serr($sal['msg']);
                }
                $sal = $sal['msg'];
            } catch (Exception $e) {
                return serr('与主服务器建立通讯通道失败,请重新尝试。');
            }
        }
        Cache::set('planjwt', $sal);
        return sok($sal);
    }
    /**
     * 同步中心请求api
     * @param  [type] $url  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function syncapi($url, $data)
    {
        $url          = SYNC_URL .'index/'. $url;
        $data['XwId'] = SYNC_ID;
        return self::sapi($url, $data);
    }

     /**
     * 同步中心请求api
     * @param  [type] $url  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function sapi($url, $data)
    {
        $data         = json_encode($data);
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: POST,GET');
        header('Access-Control-Allow-Credentials:true');
        $request = Request::instance();
        $curl    = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            // dump($data);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data),
        ));
        $output = curl_exec($curl);
        curl_close($curl);
        // dump($output);
        // exit;
        return json_decode($output, true);
    }

}
